<template>
  <el-dialog
    draggable
    overflow
    :title="titleMap[mode]"
    v-model="visible"
    :width="1200"
    destroy-on-close
    @closed="$emit('closed', mode)"
  >
    <sk-tabs type="border-card">
      <el-tab-pane ref="tab" label="基础信息">
        <el-form
          :model="form"
          :rules="rules"
          ref="dialogForm1"
          label-width="70px"
          label-position="top"
          class="formhead"
        >
          <el-row style="display: flex; align-items: center">
            <el-col :span="12" :column="4">
              <span style="font-size: 25px">{{
                form.is_sample == 1 ? "客户打样生产单" : "客户来货生产单"
              }}</span>
            </el-col>
            <el-col :span="12">
              <el-descriptions direction="vertical" border :column="4">
                <el-descriptions-item
                  label="客户订单号"
                  label-align="center"
                  align="center"
                  label-class-name="light-blue"
                >
                  <el-input v-model="form.cust_order"></el-input
                ></el-descriptions-item>
                <el-descriptions-item
                  label="编号"
                  label-align="center"
                  align="center"
                  label-class-name="light-blue"
                >
                  <el-input v-model="form.code" disabled placeholder="自动生成"></el-input
                ></el-descriptions-item>

                <el-descriptions-item
                  label="单据日期"
                  label-align="center"
                  align="center"
                  label-class-name="light-blue"
                >
                  <el-date-picker
                    v-model="form.billdate"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-descriptions-item>
                <el-descriptions-item
                  label="订单交期"
                  label-align="center"
                  align="center"
                  label-class-name="light-blue"
                >
                  <el-date-picker
                    v-model="form.delivary_date"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-form>
        <el-form
          :model="form"
          :rules="rules"
          ref="dialogForm"
          label-width="100px"
          label-position="right"
        >
          <el-row>
            <el-col :span="18">
              <el-row>
                <el-col :span="8" align="客户">
                  <el-form-item label="客户" prop="customer_id">
                    <skAutoChoose
                      v-model="form.customer.name"
                      :name="'customer'"
                      :assign="form"
                      @select="cunstomerSelect"
                    >
                    </skAutoChoose>
                  </el-form-item>
                </el-col>
                <el-col :span="8" align="联系人">
                  <el-form-item label="联系人" prop="linkman_id" class="addicon">
                    <el-select v-model="form.linkman_id" :placeholder="'先选择客户'">
                      <el-option
                        v-for="item in linkmanList"
                        :value="item.id"
                        :label="item.name + ',' + item.phone"
                        :key="item.id"
                      >
                      </el-option>
                    </el-select>
                    <el-button
                      type="info"
                      icon="ElIconPlus"
                      @click="linkmanAdd"
                      style="width: 22px; height: 24px"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="业务员" prop="salesman_id">
                    <skAutoChoose
                      v-model="form.salesman.name"
                      :name="'user'"
                      :asKey="'salesman_id'"
                      :assign="form"
                    >
                    </skAutoChoose>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="初检">
                    <el-checkbox
                      v-model="form.needInspect"
                      label=""
                      :true-label="1"
                      :false-label="0"
                    />
                    库位：
                    <div style="width: 120px">
                      <skAutoChoose
                        v-model="form.location.name"
                        :name="'location'"
                        :assign="form"
                      >
                      </skAutoChoose>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="终检">
                    <el-checkbox
                      v-model="form.needEndInspect"
                      label=""
                      :true-label="1"
                      :false-label="0"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="工艺记录" prop="process_requirements">
                    <skAutoChoose
                      v-model="form.process_requirements"
                      :params="getCompanyParams"
                      :name="'process_requirements'"
                    >
                    </skAutoChoose>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="正面" prop="inspection_requirements">
                    <el-input v-model="form.inspection_requirements" />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="客供底布">
                    <el-checkbox
                      v-model="form.customer_material"
                      label=""
                      :true-label="1"
                      :false-label="0"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生产要求" prop="remark">
                    <el-input v-model="form.remark" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="6">
              <el-col :span="24">
                <el-form-item label="经手人" prop="employee_id">
                  <skAutoChoose
                    v-model="form.employee.name"
                    :name="'user'"
                    :asKey="'employee_id'"
                    :assign="form"
                  >
                  </skAutoChoose>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="包装要求" prop="packaging_requirements">
                  <el-input v-model="form.packaging_requirements" type="textarea" />
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="6">
              <el-form-item label="内唛" prop="inside_barcode_id">
                <skAutoChoose
                  v-model="form.inside_barcode.name"
                  :name="'barcode'"
                  :asKey="'inside_barcode_id'"
                  :prepend_width="'30px'"
                  :asValue="'0'"
                  :assign="form"
                >
                  <template #append>
                    <RouterLink
                      target="_blank"
                      :to="{
                        name: 'designerBarcode',
                        query: { id: form.inside_barcode.id },
                      }"
                    >
                      <el-button type="warning" icon="ElIconEdit" /></RouterLink
                  ></template>
                </skAutoChoose>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="外唛" prop="outside_barcode_id">
                <skAutoChoose
                  v-model="form.outside_barcode.name"
                  :name="'barcode'"
                  :asKey="'outside_barcode_id'"
                  :assign="form"
                  :asValue="'0'"
                  :prepend_width="'30px'"
                >
                  <template #append>
                    <RouterLink
                      target="_blank"
                      :to="{
                        name: 'designerBarcode',
                        query: { id: form.outside_barcode.id },
                      }"
                    >
                      <el-button type="warning" icon="ElIconEdit"
                    /></RouterLink>
                  </template>
                </skAutoChoose>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="验单位" prop="check_unit_id">
                <skDicSelect v-model="form.check_unit_id" :code="'unitMM'"></skDicSelect>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="验小数" prop="check_formatter_id">
                <skDicSelect
                  v-model="form.check_formatter_id"
                  :code="'formatterNumber'"
                ></skDicSelect>
              </el-form-item>
            </el-col>
          </el-row>
          <sc-VxeTable
            ref="xGrid1"
            :gridEvts="gridEvents"
            :gridOps="gridOps"
            :data="form.details"
            :tablecode="'market_customer_storage_receive_save'"
          >
          </sc-VxeTable>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="附件">
        <sk-upload
          v-model="form.attachments"
          :limit="10"
          draggable
          tip="单个文件不要超过10M,请上传图像格式文件"
        >
        </sk-upload>
      </el-tab-pane>
    </sk-tabs>

    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>
  <linkman-add ref="saveDialog" @success="handleSuccess"> </linkman-add>
</template>

<script>
import skDicSelect from "@/components/skDicSelect";
import linkmanAdd from "./linkmanAdd";
import skAutoChoose from "@/components/skAutoChoose";
export default {
  emits: ["success", "closed"],
  components: { skDicSelect, skAutoChoose, linkmanAdd },
  props: {
    inside_barcode_id: {
      type: Number,
      default: 6,
    },
  },
  data() {
    return {
      mode: "edit",
      gridEvents: {
        copydata: ({ button }) => {
          let newRow = this.$TOOL.objCopy(button.selectRecords[0]);
          newRow.id = "key" + new Date().getTime();
          this.form.details.push(newRow);
        },
      },
      gridOps: {
        height: 300,
        columns: [
          {
            field: "material.name",
            event: {
              select: ({ e, row }) => {
                row["material"]["spec"] = e.spec;
                row["unit"] = e.uunit;
                row["unit_id"] = e.uunit_id;
              },
            },
          },
          {
            field: "color_name",
            event: {
              keyup: ({ row }) => {
                row["label_color"] = row.color_name;
              },
            },
          },
          {
            field: "custno",
            event: {
              keyup: ({ row }) => {
                row["label_material"] = row.custno;
              },
            },
          },
        ],
      },
      titleMap: {
        add: "新增",
        edit: "编辑",
      },
      linkmanList: [],
      form: {
        id: "",
        code: "",
        customer: {
          name: "",
        },
        check_formatter_id: 3,
        inside_barcode_id: 6,
        outside_barcode_id: 6,
        inside_barcode: { name: "极光通用票签" },
        outside_barcode: { name: "极光通用票签" },
        location: {
          name: "",
        },
        check_unit_id: "3",
        customer_material: 0,
        customer_id: null,
        linkman: { name: "" },
        linkman_id: "",
        salesman: { name: "" },
        employee: { name: "" },
        employee_id: 0,
        details: [],
        billdate: this.$TOOL.SYS_DATE(),
        attachments: [],
      },
      rules: {
        billdate: [{ required: true, message: "单据日期必填" }],
        customer_id: [{ required: true, message: "请选择客户" }],
        check_unit_id: [{ required: true, message: "验单位必选" }],
      },
      visible: false,
      isSaveing: false,
    };
  },
  mounted() {
    this.setDfaultEmployee();
    this.form.inside_barcode_id = this.inside_barcode_id;
    if (this.inside_barcode_id != 6) {
      this.form.outside_barcode_id = 0;
      this.form.outside_barcode.name = "";
      this.form.inside_barcode.name = "指标标签";
    }
  },
  methods: {
    //显示
    open(mode = "add") {
      this.mode = mode;
      this.visible = true;

      return this;
    },
    setDfaultEmployee() {
      let userInfo = this.$TOOL.data.get("USER_INFO");
      this.form.employee = userInfo;
      this.form.employee_id = userInfo.id;
    },
    //表单提交方法
    submit() {
      this.$refs.dialogForm.validate(async valid => {
        if (valid) {
          this.isSaveing = true;
          var res = await this.$API.market.customerStorage.save.post(this.form);
          this.isSaveing = false;
          if (res.code == 200) {
            this.$emit("success", this.form, this.mode);
            this.$emit("closed", "false");
            this.visible = false;
            this.$message.success("操作成功");
          }
        }
      });
    },
    async getItems(id) {
      var res = await this.$API.market.customerStorage.list.get({
        filter: [{ main_id: id }],
      });
      if (res.code == 200) {
        let maindata = res.data.rows[0].main;
        Object.assign(this.form, this.$TOOL.removeNull(maindata));
        this.form.details = res.data.rows;

        if (maindata.outside_barcode == null) {
          maindata.outside_barcode = {};
        }
        if (maindata.inside_barcode == null) {
          maindata.inside_barcode = {};
        }
      }
    },
    linkmanAdd() {
      this.$refs.dialogForm.validateField("customer_id", err => {
        if (err) {
          this.$refs.saveDialog
            .setData(this.form.customer.name, this.form.customer_id)
            .open("add");
        }
      });
    },
    getCompanyParams() {
      return { "open_card.customer_id": this.form.customer_id ?? 0 };
    },
    async valCompany() {
      let res = true;
      await this.$refs.dialogForm.validateField("customer_id", err => {
        res = err;
      });
      return res;
    },
    linkmanGet(company_id) {
      this.$API.basedata.businessCompany.linkmanGet
        .get({
          filter: [{ company_id: company_id }],
        })
        .then(v => {
          this.linkmanList = v.data;
        });
    },
    cunstomerSelect(data) {
      let userInfo = this.$TOOL.data.get("USER_INFO");
      this.linkmanList = data.link_mans ?? [];
      this.billtradeList = data.billtrade ?? [];
      this.credit_limit = data.credit_limit;
      this.ARBalance = data.ARBalance;
      this.form.salesman = data.salesman ?? userInfo;
      this.form.salesman_id = data.salesman_id ?? userInfo.id;
      this.form.department_id = data.salesman?.department_id ?? userInfo.department_id;
      //初始化联系人
      if ((data.link_mans ?? []).length == 0) {
        this.loadDefaultLinkMan();
      } else {
        this.linkmanList = data.link_mans;
        this.form.linkman_id = this.linkmanList[0].id;
      }
    },
    loadDefaultLinkMan() {
      let userInfo = this.$TOOL.data.get("USER_INFO");
      this.handleSuccess({
        id: userInfo.employee_id,
        name: userInfo.username,
        phone: userInfo.phone,
      });
    },
    handleSuccess(data) {
      this.linkmanList.push(data);
      this.form.linkman_id = data.id;
    },
    setFormData(data) {
      Object.assign(this.form, data);
    },
    //表单注入数据
    setData(data) {
      this.form.customer = data.customer;
      this.form.customer_id = data.customer_id;
      this.linkmanGet(this.form.customer_id);
      this.getItems(data.main.id);
    },
  },
};
</script>
<style>
.addicon .el-input {
  width: calc(100% - 25px);
}

.addicon .el-input__wrapper {
  border-top-right-radius: 0px;
  border-bottom-right-radius: 0px;
}

.addicon .el-button--small {
  border-top-left-radius: 0px;
  border-bottom-left-radius: 0px;
}
</style>
